<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elasticsearch聚合分析深度指南</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Noto Sans SC', Tahoma, Arial, Roboto, "Droid Sans", "Helvetica Neue", "Droid Sans Fallback", "Heiti SC", "Hiragino Sans GB", Simsun, sans-serif;
            color: #333;
            line-height: 1.6;
        }
        .header-font {
            font-family: 'Noto Serif SC', serif;
        }
        .drop-cap::first-letter {
            font-size: 4.5rem;
            line-height: 0.8;
            float: left;
            margin-right: 1rem;
            margin-top: 0.3rem;
            font-weight: 700;
            color: #4f46e5;
        }
        .code-block {
            background-color: #2d3748;
            color: #f7fafc;
            border-radius: 0.5rem;
            padding: 1.5rem;
            position: relative;
        }
        .code-block:before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(to bottom, #4f46e5, #10b981);
            border-radius: 0.5rem 0 0 0.5rem;
        }
        .example-card {
            transition: all 0.3s ease;
            border-left: 4px solid #4f46e5;
        }
        .example-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        .feature-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4f46e5, #8b5cf6);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }
        .nav-link {
            position: relative;
        }
        .nav-link:after {
            content: '';
            position: absolute;
            width: 0;
            height: 2px;
            bottom: -2px;
            left: 0;
            background-color: #4f46e5;
            transition: width 0.3s ease;
        }
        .nav-link:hover:after {
            width: 100%;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Hero Section -->
    <div class="relative bg-gradient-to-r from-indigo-500 to-purple-600 py-20 px-6 sm:px-12 lg:px-24">
        <div class="max-w-5xl mx-auto text-center">
            <h1 class="text-4xl sm:text-5xl lg:text-6xl font-bold text-white header-font mb-6 leading-tight">
                Elasticsearch聚合分析
            </h1>
            <p class="text-xl text-indigo-100 max-w-3xl mx-auto mb-10">
                解锁大数据分析的强大力量，实时洞察商业价值
            </p>
            <div class="flex flex-col sm:flex-row justify-center gap-4">
                <a href="#introduction" class="bg-white text-indigo-600 px-6 py-3 rounded-lg font-medium hover:bg-indigo-50 transition duration-300 shadow-lg">
                    <i class="fas fa-book-open mr-2"></i> 开始学习
                </a>
                <a href="#examples" class="bg-indigo-800 text-white px-6 py-3 rounded-lg font-medium hover:bg-indigo-700 transition duration-300 shadow-lg">
                    <i class="fas fa-code mr-2"></i> 查看示例
                </a>
            </div>
        </div>
        <div class="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-gray-50 to-transparent"></div>
    </div>

    <!-- Navigation -->
    <div class="sticky top-0 bg-white shadow-sm z-10">
        <div class="max-w-6xl mx-auto px-6 py-4">
            <div class="flex justify-between items-center">
                <div class="text-xl font-bold text-indigo-600 header-font">
                    <i class="fas fa-chart-bar mr-2"></i> ES聚合指南
                </div>
                <div class="hidden md:flex space-x-8">
                    <a href="#introduction" class="nav-link text-gray-700 hover:text-indigo-600">概述</a>
                    <a href="#setup" class="nav-link text-gray-700 hover:text-indigo-600">数据准备</a>
                    <a href="#examples" class="nav-link text-gray-700 hover:text-indigo-600">示例</a>
                    <a href="#applications" class="nav-link text-gray-700 hover:text-indigo-600">应用场景</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-4xl mx-auto px-6 py-12">
        <!-- Introduction -->
        <section id="introduction" class="mb-20">
            <h2 class="text-3xl font-bold mb-6 text-gray-800 header-font">
                <i class="fas fa-lightbulb text-yellow-400 mr-3"></i> 聚合功能概述
            </h2>
            <div class="bg-white rounded-xl shadow-md p-8 mb-10">
                <p class="drop-cap text-lg text-gray-700 leading-relaxed">
                    Elasticsearch 的聚合（Aggregation）功能是一种强大的实时数据分析工具，它允许用户在搜索过程中对数据进行统计计算和数据汇总。聚合功能非常适合进行实时分析，因为它可以快速处理大规模的数据集，并生成有用的统计信息，如平均值、最大值、最小值、总和、计数、直方图等。
                </p>
            </div>

            <div class="grid md:grid-cols-4 gap-6 mb-12">
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100 text-center">
                    <div class="feature-icon mx-auto">
                        <i class="fas fa-calculator"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-2 text-gray-800">度量聚合</h3>
                    <p class="text-gray-600">对文档字段进行数值计算</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100 text-center">
                    <div class="feature-icon mx-auto">
                        <i class="fas fa-bucket"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-2 text-gray-800">桶聚合</h3>
                    <p class="text-gray-600">根据规则将文档分组</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100 text-center">
                    <div class="feature-icon mx-auto">
                        <i class="fas fa-faucet"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-2 text-gray-800">管道聚合</h3>
                    <p class="text-gray-600">基于其他聚合再聚合</p>
                </div>
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100 text-center">
                    <div class="feature-icon mx-auto">
                        <i class="fas fa-table"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-2 text-gray-800">矩阵聚合</h3>
                    <p class="text-gray-600">分析多字段关系</p>
                </div>
            </div>

            <!-- Visualization -->
            <div class="bg-white rounded-xl shadow-md p-8 mb-10">
                <h3 class="text-2xl font-semibold mb-6 text-gray-800 header-font">聚合类型关系图</h3>
                <div class="mermaid">
                    graph TD
                        A[聚合] --> B[度量聚合]
                        A --> C[桶聚合]
                        A --> D[管道聚合]
                        A --> E[矩阵聚合]
                        B --> F[求和]
                        B --> G[平均值]
                        B --> H[最大值]
                        B --> I[最小值]
                        C --> J[Terms]
                        C --> K[日期直方图]
                        C --> L[范围]
                        D --> M[移动平均]
                        D --> N[导数]
                        E --> O[矩阵统计]
                        E --> P[矩阵百分位]
                </div>
            </div>
        </section>

        <!-- Setup Data -->
        <section id="setup" class="mb-20">
            <h2 class="text-3xl font-bold mb-8 text-gray-800 header-font">
                <i class="fas fa-database text-blue-500 mr-3"></i> 1. 设置数据和索引
            </h2>
            <div class="bg-white rounded-xl shadow-md p-8 mb-10">
                <p class="text-lg text-gray-700 leading-relaxed mb-6">
                    在开始聚合之前，我们需要先准备一些数据并将其索引到 Elasticsearch 中。假设我们有一个电子商务系统的数据集，其中包含了订单信息。每个订单有以下字段：
                </p>
                
                <div class="grid md:grid-cols-2 gap-6 mb-8">
                    <div class="bg-indigo-50 p-6 rounded-lg">
                        <h4 class="font-semibold text-indigo-800 mb-3">订单字段结构</h4>
                        <ul class="space-y-2">
                            <li class="flex items-start">
                                <i class="fas fa-tag text-indigo-500 mt-1 mr-2"></i>
                                <span><code class="bg-indigo-100 px-2 py-1 rounded">order_id</code>: 订单编号</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-user text-indigo-500 mt-1 mr-2"></i>
                                <span><code class="bg-indigo-100 px-2 py-1 rounded">customer_id</code>: 客户编号</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-calendar text-indigo-500 mt-1 mr-2"></i>
                                <span><code class="bg-indigo-100 px-2 py-1 rounded">order_date</code>: 订单日期</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-money-bill-wave text-indigo-500 mt-1 mr-2"></i>
                                <span><code class="bg-indigo-100 px-2 py-1 rounded">total_amount</code>: 订单总金额</span>
                            </li>
                            <li class="flex items-start">
                                <i class="fas fa-boxes text-indigo-500 mt-1 mr-2"></i>
                                <span><code class="bg-indigo-100 px-2 py-1 rounded">product_category</code>: 产品类别</span>
                            </li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold text-indigo-800 mb-3">索引创建示例</h4>
                        <div class="code-block">
                            <pre class="overflow-x-auto text-sm">
                                <code class="text-gray-200">
PUT /orders
{
  "mappings": {
    "properties": {
      "order_id": { "type": "keyword" },
      "customer_id": { "type": "keyword" },
      "order_date": { "type": "date" },
      "total_amount": { "type": "double" },
      "product_category": { "type": "keyword" }
    }
  }
}</code>
                            </pre>
                        </div>
                    </div>
                </div>

                <h4 class="font-semibold text-indigo-800 mb-3 mt-6">插入示例数据</h4>
                <div class="code-block mb-4">
                    <pre class="overflow-x-auto text-sm">
                        <code class="text-gray-200">
POST /orders/_doc/1
{
  "order_id": "1001",
  "customer_id": "C001",
  "order_date": "2024-08-30T12:01:23",
  "total_amount": 250.5,
  "product_category": "electronics"
}

POST /orders/_doc/2
{
  "order_id": "1002",
  "customer_id": "C002",
  "order_date": "2024-08-30T13:15:00",
  "total_amount": 130.75,
  "product_category": "books"
}</code>
                    </pre>
                </div>
                <p class="text-gray-500 text-sm"><i class="fas fa-info-circle mr-2"></i>为了简洁，这里只展示了两个示例文档，实际应用中会有更多数据。</p>
            </div>
        </section>

        <!-- Examples -->
        <section id="examples" class="mb-20">
            <h2 class="text-3xl font-bold mb-8 text-gray-800 header-font">
                <i class="fas fa-code text-green-500 mr-3"></i> 2. 执行聚合查询
            </h2>

            <div class="space-y-12">
                <!-- Example 1 -->
                <div class="example-card bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-start">
                        <div class="bg-green-100 text-green-800 rounded-full w-8 h-8 flex items-center justify-center mr-4 mt-1 flex-shrink-0">
                            <span class="font-bold">1</span>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-3 text-gray-800">计算总订单金额</h3>
                            <p class="text-gray-700 mb-4">
                                我们可以使用 <strong>度量聚合</strong> 来计算所有订单的总金额。
                            </p>
                            <div class="code-block mb-4">
                                <pre class="overflow-x-auto text-sm">
                                    <code class="text-gray-200">
POST /orders/_search
{
  "size": 0,
  "aggs": {
    "total_sales": {
      "sum": {
        "field": "total_amount"
      }
    }
  }
}</code>
                                </pre>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-800 mb-2 flex items-center">
                                    <i class="fas fa-info-circle mr-2"></i> 解释
                                </h4>
                                <ul class="text-blue-800 space-y-1">
                                    <li><code>size: 0</code>：不返回文档，仅返回聚合结果</li>
                                    <li><code>aggs</code>：定义聚合查询。<code>total_sales</code> 是自定义的聚合名称</li>
                                    <li><code>sum</code>：度量聚合，用于计算 <code>total_amount</code> 字段的总和</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Example 2 -->
                <div class="example-card bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-start">
                        <div class="bg-green-100 text-green-800 rounded-full w-8 h-8 flex items-center justify-center mr-4 mt-1 flex-shrink-0">
                            <span class="font-bold">2</span>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-3 text-gray-800">按产品类别计算销售总额</h3>
                            <p class="text-gray-700 mb-4">
                                使用 <strong>桶聚合</strong> 和 <strong>度量聚合</strong> 的组合，我们可以按 <code>product_category</code> 进行分组，并计算每个类别的销售总额。
                            </p>
                            <div class="code-block mb-4">
                                <pre class="overflow-x-auto text-sm">
                                    <code class="text-gray-200">
POST /orders/_search
{
  "size": 0,
  "aggs": {
    "sales_by_category": {
      "terms": {
        "field": "product_category"
      },
      "aggs": {
        "total_sales": {
          "sum": {
            "field": "total_amount"
          }
        }
      }
    }
  }
}</code>
                                </pre>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-800 mb-2 flex items-center">
                                    <i class="fas fa-info-circle mr-2"></i> 解释
                                </h4>
                                <ul class="text-blue-800 space-y-1">
                                    <li><code>terms</code> 聚合用于将数据按 <code>product_category</code> 字段的值进行分组</li>
                                    <li>每个分组中，计算该类别下所有订单的 <code>total_amount</code> 总和</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Example 3 -->
                <div class="example-card bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-start">
                        <div class="bg-green-100 text-green-800 rounded-full w-8 h-8 flex items-center justify-center mr-4 mt-1 flex-shrink-0">
                            <span class="font-bold">3</span>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-3 text-gray-800">按日期范围计算每日销售总额</h3>
                            <p class="text-gray-700 mb-4">
                                使用 <strong>日期直方图（Date Histogram）桶聚合</strong>，可以按天计算销售总额。
                            </p>
                            <div class="code-block mb-4">
                                <pre class="overflow-x-auto text-sm">
                                    <code class="text-gray-200">
POST /orders/_search
{
  "size": 0,
  "aggs": {
    "daily_sales": {
      "date_histogram": {
        "field": "order_date",
        "calendar_interval": "day"
      },
      "aggs": {
        "total_sales": {
          "sum": {
            "field": "total_amount"
          }
        }
      }
    }
  }
}</code>
                                </pre>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-800 mb-2 flex items-center">
                                    <i class="fas fa-info-circle mr-2"></i> 解释
                                </h4>
                                <ul class="text-blue-800 space-y-1">
                                    <li><code>date_histogram</code> 桶聚合将数据按 <code>order_date</code> 字段的日历日间隔分组</li>
                                    <li>每日销售总额由 <code>sum</code> 度量聚合计算</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Example 4 -->
                <div class="example-card bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-start">
                        <div class="bg-green-100 text-green-800 rounded-full w-8 h-8 flex items-center justify-center mr-4 mt-1 flex-shrink-0">
                            <span class="font-bold">4</span>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-3 text-gray-800">按产品类别和日期范围进行分组分析</h3>
                            <p class="text-gray-700 mb-4">
                                可以将多个桶聚合和度量聚合组合起来，进行更复杂的分析。
                            </p>
                            <div class="code-block mb-4">
                                <pre class="overflow-x-auto text-sm">
                                    <code class="text-gray-200">
POST /orders/_search
{
  "size": 0,
  "aggs": {
    "sales_by_category_and_date": {
      "terms": {
        "field": "product_category"
      },
      "aggs": {
        "daily_sales": {
          "date_histogram": {
            "field": "order_date",
            "calendar_interval": "day"
          },
          "aggs": {
            "total_sales": {
              "sum": {
                "field": "total_amount"
              }
            }
          }
        }
      }
    }
  }
}</code>
                                </pre>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-800 mb-2 flex items-center">
                                    <i class="fas fa-info-circle mr-2"></i> 解释
                                </h4>
                                <ul class="text-blue-800 space-y-1">
                                    <li>第一个 <code>terms</code> 桶聚合按 <code>product_category</code> 分组</li>
                                    <li>第二个 <code>date_histogram</code> 桶聚合按 <code>order_date</code> 分组</li>
                                    <li>最后使用 <code>sum</code> 度量聚合来计算每个类别每天的销售总额</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Example 5 -->
                <div class="example-card bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-start">
                        <div class="bg-green-100 text-green-800 rounded-full w-8 h-8 flex items-center justify-center mr-4 mt-1 flex-shrink-0">
                            <span class="font-bold">5</span>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-3 text-gray-800">计算移动平均值</h3>
                            <p class="text-gray-700 mb-4">
                                使用 <strong>管道聚合</strong> 来基于前面聚合结果计算移动平均值。
                            </p>
                            <div class="code-block mb-4">
                                <pre class="overflow-x-auto text-sm">
                                    <code class="text-gray-200">
POST /orders/_search
{
  "size": 0,
  "aggs": {
    "daily_sales": {
      "date_histogram": {
        "field": "order_date",
        "calendar_interval": "day"
      },
      "aggs": {
        "total_sales": {
          "sum": {
            "field": "total_amount"
          }
        },
        "moving_avg_sales": {
          "moving_avg": {
            "buckets_path": "total_sales"
          }
        }
      }
    }
  }
}</code>
                                </pre>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <h4 class="font-semibold text-blue-800 mb-2 flex items-center">
                                    <i class="fas fa-info-circle mr-2"></i> 解释
                                </h4>
                                <ul class="text-blue-800 space-y-1">
                                    <li><code>moving_avg</code> 聚合计算基于前面 <code>total_sales</code> 聚合结果的移动平均值</li>
                                    <li><code>buckets_path</code> 指定需要计算移动平均值的聚合结果路径</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Applications -->
        <section id="applications" class="mb-20">
            <h2 class="text-3xl font-bold mb-8 text-gray-800 header-font">
                <i class="fas fa-rocket text-purple-500 mr-3"></i> 3. 实时数据分析的应用场景
            </h2>
            <div class="bg-white rounded-xl shadow-md p-8">
                <p class="text-lg text-gray-700 leading-relaxed mb-8">
                    通过 Elasticsearch 的聚合功能，可以实现多种实时数据分析的应用：
                </p>
                
                <div class="grid md:grid-cols-3 gap-6">
                    <div class="bg-gradient-to-br from-purple-50 to-indigo-50 p-6 rounded-lg">
                        <div class="text-purple-600 text-2xl mb-3">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-2 text-gray-800">实时销售数据监控</h3>
                        <p class="text-gray-600">计算实时的销售额、销售趋势等数据，用于业务决策。</p>
                    </div>
                    <div class="bg-gradient-to-br from-blue-50 to-cyan-50 p-6 rounded-lg">
                        <div class="text-blue-600 text-2xl mb-3">
                            <i class="fas fa-user-edit"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-2 text-gray-800">用户行为分析</h3>
                        <p class="text-gray-600">分析用户的行为数据，如点击率、页面访问深度等。</p>
                    </div>
                    <div class="bg-gradient-to-br from-red-50 to-pink-50 p-6 rounded-lg">
                        <div class="text-red-600 text-2xl mb-3">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <h3 class="text-xl font-semibold mb-2 text-gray-800">异常检测</h3>
                        <p class="text-gray-600">实时检测数据中的异常情况（如异常高的订单金额、异常频繁的访问行为等）。</p>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- Footer -->
    <footer class="bg-gray-900 text-gray-300 py-12 px-6">
        <div class="max-w-4xl mx-auto">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <h3 class="text-xl font-bold text-white mb-2">技术小馆</h3>
                    <p class="text-gray-400">专业的Elasticsearch技术指南</p>
                </div>
                <div>
                    <a href="http://www.yuque.com/jtostring" class="text-indigo-300 hover:text-white transition duration-300">
                        <i class="fas fa-globe mr-2"></i> http://www.yuque.com/jtostring
                    </a>
                </div>
            </div>
            <div class="border-t border-gray-800 mt-8 pt-8 text-center text-gray-500 text-sm">
                &copy; 2023 技术小馆. 保留所有权利.
            </div>
        </div>
    </footer>

    <!-- Mermaid.js -->
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            mermaid.initialize({
                startOnLoad: true,
                theme: 'default',
                flowchart: {
                    useMaxWidth: false,
                    htmlLabels: true,
                    curve: 'basis'
                }
            });
            
            // 平滑滚动
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    document.querySelector(this.getAttribute('href')).scrollIntoView({
                        behavior: 'smooth'
                    });
                });
            });
        });
    </script>
</body>
</html>